from io import StringIO
from random import sample

from django.http import HttpRequest
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.


# def index(request:HttpRequest):
#     fruits = ['苹果', '香蕉', '菠萝', '草莓', '西瓜', '榴莲', '火龙果', '猕猴桃', '山竹']
#     context = {
#         'fruits': sample(fruits, 3),
#         'greeting': 'hello，good morning'
#     }
#
#     return render(request, 'index.html', context)

# def index(request:HttpRequest):
#     fruits = ['苹果', '香蕉', '菠萝', '草莓', '西瓜', '榴莲', '火龙果', '猕猴桃', '山竹']
#     content = StringIO()
#     content.write('<h2>今日推荐水果</h2>\r\n')
#     content.write('<hr>\r\n')
#     content.write('<ul>\r\n')
#     for fruit in sample(fruits, 3):
#         content.write(f'\t<li>{fruit}</li>\r\n')
#     content.write('</ul>\r\n')
#     return HttpResponse(content.getvalue())
from polls.models import Subject, Teacher


def index(request):
    """首页"""
    queryset = Subject.objects.all()
    context = {
        'subjects': queryset
    }

    return render(request, 'index.html', context)


def show_teachers(request):
    """显示指定学科的老师"""
    try:
        sno = request.GET['sno']
        subject = Subject.objects.get(no=sno)
        queryset = Teacher.objects.filter(subject__no=sno)
        context = {
            'subject': subject,
            'teachers': queryset
        }

        return render(request, 'teachers.html', context)
    except (KeyError, ValueError, Subject.DoseNotExist):
        return redirect('/')


def praise(request):

    tno = request.GET.get('tno', '0')
    sno = request.GET.get('sno', '0')
    teacher = Teacher.objects.get(no=tno)
    teacher.good_count += 1
    teacher.save()
    return redirect(f'/teachers/?sno={sno}')


def criticize(request):

    tno = request.GET.get('tno', '0')
    sno = request.GET.get('sno', '0')
    teacher = Teacher.objects.get(no=tno)
    teacher.bad_count += 1
    teacher.save()
    return redirect(f'/teachers/?sno={sno}')

